package com.matt.controller.api.web;

import com.dotflat.fin.utils.excelUtil.ExcelUtil;
import com.matt.commons.constant.CommonConstant;
import com.matt.commons.dto.sso.AreaDTO;
import com.matt.controller.po.ClienteleSortCountPO;
import com.matt.controller.po.ContractImportPO;
import com.matt.domain.Clientele;
import com.matt.domain.Contract;
import com.matt.ext.aliyun.OSSProcessService;
import com.matt.foundation.constant.ClienteleConstant;
import com.matt.foundation.constant.ContractConstant;
import com.matt.commons.dto.sso.StaffDTO;
import com.matt.foundation.constant.PermissionConstant;
import com.matt.foundation.model.ErrorCode;
import com.matt.foundation.model.StatusResponse;
import com.matt.foundation.query.ContractQuery;
import com.matt.foundation.utils.DateUtil;
import com.matt.foundation.vo.ContractExportVo;
import com.matt.foundation.vo.ContractVo;
import com.matt.service.AnalysisService;
import com.matt.service.ClienteleService;
import com.matt.service.ContractService;
import com.matt.remoteCall.SsoCallService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.transaction.Transactional;
import java.io.File;
import java.util.*;

import static com.matt.foundation.constant.AnalysisConstant.UN_NORMAL_STOP;

/**
 * *******************
 * description:合同控制器
 * Created by Ron
 * from com.matt
 * on 2018/6/14 0014.
 * ********************
 */
@RestController
@RequestMapping("/web/contract")
@Api(tags = "CRM - 合同")
public class ContractController {

    @Autowired
    private ContractService contractService;

    @Autowired
    private ClienteleService clienteleService;

    @Autowired
    private SsoCallService ssoCallService;

    @Autowired
    private AnalysisService analysisService;

    @Autowired
    private OSSProcessService ossProcessService;

    @Value("${aliyun.oss.fileServerPrefix}")
    private String IMG_SERVICE_PREFIX;
    /**
     * 新增
     *
     * @param ticket
     * @param contract
     * @param productRecords
     * @return
     */
    @RequestMapping(value = "/edit")
    @ApiOperation(value = "修改合同", httpMethod = "POST")
    public StatusResponse edit(@RequestHeader String ticket, Contract contract, String productRecords) {
        return StatusResponse.success();
    }


    /**
     * 新增
     *
     * @param ticket
     * @param contract
     * @param productRecords
     * @return
     */
    @RequestMapping(value = "/add")
    @ApiOperation(value = "增加合同", httpMethod = "POST")
    public StatusResponse add(@RequestHeader String ticket, Contract contract, String productRecords) {

        StaffDTO staff = ssoCallService.getStaffDTO(ticket);

        //校验实付金额和合同金额
        Boolean flag = contractService.ckeckout(contract.getPracticalAmount(), productRecords);
        //校验合同编号是否重复        
        Boolean checkCode = contractService.checkConstractCode(contract.getAreaId(), contract.getCode());
        if (flag == false) {
            return StatusResponse.error(ErrorCode.CONTRACT_MONEY_ERROR, "实付金额大于总金额！");
        }else if(checkCode == false) {
        	return StatusResponse.error(ErrorCode.CONTRACT_CODE_ERROR, "园区已存在相同合同编号，请重新输入！");
        } else {
            Contract vo = contractService.save(staff, contract, productRecords);
            //查询客户合同不为已中止的已付清的合同
            Long count = contractService.findByStatusAndPayStatus(contract.getClienteleId(), ContractConstant.Status.STOP.codeOf(), ContractConstant.PayStatus.NON_PAY.codeOf());
            Clientele clientele = clienteleService.getById(contract.getClienteleId());
            if (count > 0) {
                clientele.setStatus(ClienteleConstant.Status.ORDER_CASH.codeOf());
                clientele.setStatusVal(ClienteleConstant.Status.ORDER_CASH.valueOf());
            } else {
                clientele.setStatus(ClienteleConstant.Status.SUCCESS.codeOf());
                clientele.setStatusVal(ClienteleConstant.Status.SUCCESS.valueOf());
            }

            //封装客户状态信息
            vo.setClienteleStatus(clientele.getStatus());
            vo.setSignStatus(clientele.getSignStatus());
            clienteleService.saveOrigin(clientele);
            return StatusResponse.success(vo);
        }

    }
    @ApiOperation(value = "导入多个合同")
    @PostMapping("/importAdd")
    @Transactional(rollbackOn = RuntimeException.class)
    public StatusResponse importChild(@RequestHeader String ticket,
                                                             @RequestParam MultipartFile file,String areaId) throws Exception{
        StaffDTO staff = ssoCallService.getStaffDTO(ticket);
        if (Objects.nonNull(areaId)){
            //替换掉园区ID
            staff.setAreaId(areaId);
        }
        ExcelUtil<ContractImportPO> util = new ExcelUtil<ContractImportPO>(ContractImportPO.class);
        List<ContractImportPO> importExcel = util.importExcel(file.getInputStream());
        clienteleService.importAdd(staff,importExcel);
        return StatusResponse.success("");
    }

    /**
     * 1.全部合同
     * 2.我的合同
     * 3.待回款合同
     * 4.输入查询
     * 备注：
     * 我的合同>>>>>stuffId is not null
     *
     * @param contractQuery
     * @param pageable
     * @return
     */
    @RequestMapping(value = "/page")
    @ApiOperation(value = "分页查询", httpMethod = "GET")
    public StatusResponse findByCondition(@RequestHeader String ticket,ContractQuery contractQuery, Pageable pageable) {
        StaffDTO staff = ssoCallService.getStaffDTO(ticket);
        Page<ContractVo> page;
        //判断是否有管理全部班级权限
        if ( ssoCallService.checkStaffPermission(ticket,new String[]{PermissionConstant.TEACH_CLASSES_FULL }) ){
            page = contractService.findByCondition(contractQuery, pageable);
        }else if (ssoCallService.checkStaffPermission(ticket,new String[]{PermissionConstant.TEACH_CLASSES_SALES })){
            contractQuery.setStaffId(staff.getId());
            page = contractService.findByCondition(contractQuery, pageable);
        }else {
            page = new PageImpl<>(new ArrayList<>(), pageable, 0);
        }
        return StatusResponse.success(page);
    }

    //按月统计园区crm线索到店情况 渠道分布，转化客户率，跟进率
    @RequestMapping(value = "/export_list")
    @ApiOperation(value = "导出园区合同", httpMethod = "GET", response = Integer.class)
    public StatusResponse clienteleSortCount(@RequestHeader String ticket,ContractQuery contractQuery) throws  Exception{
        AreaDTO areaDTO = ssoCallService.getAreaDTO(ticket);
        List<ContractExportVo> list = contractService.findByConditionExport(contractQuery);
        ExcelUtil<ContractExportVo> util = new ExcelUtil<ContractExportVo>(ContractExportVo.class);
        File outputFile = new File(util.exportExcel(list, "参数数据") );
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;

        String uploadPath = "teach/file/children_export_excel/" + DateTime.now().toString("yyyy-MM") + "/"+year+"年"+month+"月"+areaDTO.getName()+"合同导出.xlsx" ;
        String relativePath = ossProcessService.aliyunOssUpload(uploadPath, outputFile);
        String uploadedResult = IMG_SERVICE_PREFIX + relativePath;

        outputFile.deleteOnExit();
        outputFile.delete();
        return StatusResponse.success(uploadedResult);
    }
    /**
     * 查询孩子及对应的合同
     *
     * @param areaId
     * @param sysChildName 孩子的名字
     * @return
     */
    @RequestMapping(value = "/find_contract_sysChildName")
    @ApiOperation(value = "查询孩子及对应的合同", httpMethod = "GET")
    public StatusResponse findContractByChildName(String areaId, String sysChildName) {
        return StatusResponse.success(contractService.findContractBySyschildName(areaId, sysChildName));
    }

    /**
     * 中止合同
     *
     * @param contractId      合同id
     * @param breakDownReason
     * @param breakDownRemark
     * @return
     */
    @RequestMapping(value = "/break_down")
    @ApiOperation(value = "中止合同", httpMethod = "POST")
    public StatusResponse breakDown(@RequestHeader(CommonConstant.TICKET) String ticket, String contractId, String breakDownReason, String breakDownRemark) {

        StaffDTO staff = ssoCallService.getStaffDTO(ticket);

        Contract contract = contractService.breakDown(staff, contractId, breakDownReason, breakDownRemark);
        //处理教务系统逻辑
        String staffId = staff.getId();
        contractService.endTeachRoll(contract, staffId);
        //处理数据经营系统，添加结束客户
        analysisService.createEndClient(contract.getClienteleId(), UN_NORMAL_STOP, contract.getAreaId(), new Date());
        return StatusResponse.success(contract);
    }

    /**
     * 查询合同详情
     *
     * @param contractId 合同id
     * @return
     */
    @RequestMapping(value = "/detail")
    @ApiOperation(value = "查询合同详情", httpMethod = "GET")
    public StatusResponse detail(String contractId) {
        return StatusResponse.success(contractService.details(contractId));
    }

    /**
     * 查询合同
     *
     * @param areaId
     * @param contractTitle 合同标题
     * @return
     */
    //2019-01-09删除
//    @RequestMapping(value = "/find_byName")
//    public StatusResponse findByNameString(String areaId, String contractTitle) {
//        List<Contract> contracts = contractService.findByName(areaId, contractTitle);
//        if (contracts.size() <= 0)
//            return StatusResponse.error(ErrorCode.CONTRACT_NOT_EXIST, "合同不存在");
//        return StatusResponse.success();
//    }


    /**
     * 修改合同负责人
     *
     * @param staffId
     * @param staffName
     * @param contractId
     * @return
     */
    @RequestMapping(value = "/update_contract_staff")
    @ApiOperation(value = "修改合同负责人", httpMethod = "GET")
    public StatusResponse updateContractStaff(@RequestHeader String ticket, String staffId, String staffName, String contractId) {

        StaffDTO operator = ssoCallService.getStaffDTO(ticket);
        StaffDTO newStaff = ssoCallService.getStaffDTO(ticket, staffId);

        return StatusResponse.success(contractService.updateContractStaffInfo(operator, newStaff, contractId));
    }

    /**
     * 早教消课
     *
     * @param clienteleId
     * @param num
     * @return
     */
    @RequestMapping(value = "/reduce_sat_num")
    @ApiOperation(value = "早教消课", httpMethod = "POST")
    public StatusResponse reduceSatNum(String clienteleId, Integer num) {
        return StatusResponse.success(contractService.reduceSatNum(clienteleId, num));
    }

    @RequestMapping(value = "/pay_info")
    @ApiOperation(value = "支付信息", httpMethod = "GET")
    public StatusResponse getPayTotal(String productJson){
        return StatusResponse.success(contractService.getPayTotal(productJson));
    }
    
    @RequestMapping(value = "/check_contract_code")
    @ApiOperation(value = "检查合同编号是否存在", httpMethod = "GET")
    public StatusResponse checkContractCode(@RequestHeader String ticket,String areaId,String contractCode){
    	
    	boolean checkCode = contractService.checkConstractCode(areaId,contractCode);
    	if(checkCode == false) {
        	return StatusResponse.error(ErrorCode.CONTRACT_CODE_ERROR, "园区已存在相同合同编号，请重新输入！");
        }
    		return StatusResponse.success(checkCode);
    	    	
        
    }
    
    @RequestMapping(value = "/find_by_clienteleId")
    @ApiOperation(value = "根据客户id查询合同列表", httpMethod = "GET")
    public StatusResponse findListByClientId(@RequestHeader String ticket,String clienteleId){

        StaffDTO staff = ssoCallService.getStaffDTO(ticket);

        return StatusResponse.success(contractService.findListByClienteleId(staff.getAreaId(), clienteleId));
    }
    
    @RequestMapping(value = "/freeze_contract")
    @ApiOperation(value = "冻结合同", httpMethod = "POST")
    public StatusResponse freezeContract(@RequestHeader String ticket, String clienteleId,String contractId,String content){

        StaffDTO staff = ssoCallService.getStaffDTO(ticket);

        return contractService.freezeContract(staff, clienteleId, contractId, content);

    }

    @RequestMapping(value = "/unfreeze_contract")
    @ApiOperation(value = "解冻合同", httpMethod = "POST")
    public StatusResponse unfreezeContract(@RequestHeader String ticket,String clienteleId,String contractId){

        StaffDTO staff = ssoCallService.getStaffDTO(ticket);

        return contractService.unfreezeContract(staff, clienteleId, contractId);
    	    	       
    }
}
